import {layui} from 'layui'
import moment from 'moment'
import {createPasteExcelHandler} from '../utils/excel'
import App from './App'
import {createApp, use} from 'friendly-petite-vue'


use(Layui)
use(MiniUI)

const store = {
    excelData: []
}

layui.use(['table', 'layer'], function(){
    createApp({
        layui: {table: this.table, layer: this.layer},
        mini, 
        store,
        components: {App}
    }).mount()
})


function convert2DateString(datetime?: number): string {
    return datetime ? moment(datetime).format('yyyy/MM/DD HH:mm:ss') : ''
}


const cols = [[
    {type:'numbers', title: '序号', width: 80},
    {field: 'nid', hide: true},
    {field: 'srcCdwbh9', title: '原客户编码前9位', width: 200},
    {field: 'dstCdwbh9', title: '新客户编码前9位', width: 200}
]]




layui.use(['table', 'layer', 'form'], function(){

    // mimic import
    const {PetiteVue, moment, MiniGridHelper, _, axios, mini} = window
    const {table, layer, form} = this



    var mgh = 
    let search = null

    let cols = [[
        {type:'numbers', title: '序号', width: 80},
        {field: 'nid', hide: true},
        {field: 'srcCdwbh9', title: '原客户编码前9位', width: 200},
        {field: 'dstCdwbh9', title: '新客户编码前9位', width: 200},
    ]]
    let tmpStatusTable = null

    PetiteVue.createApp({
        mounted() {
            window.handleRenderer = ({value}) => convert2DateString(value)
            search = mgh.searchOn(this.$refs.datagrid.id, {height: 400, width: 600})

            form.on('select(tmpStatus)', ({value: status}) => {
                tmpStatusTable.reload({
                    where: {status},
                    page: {curr: 1}
                })
            })
            tmpStatusTable = table.render({
                elem: '#tmpStatusTable',
                height: 500,
                url: '/cjCdwbh9Rel/tmpSearch',
                autoSort: false,
                page: true,
                limit: 50,
                limits: [20, 50, 100, 200],
                cols: cols
            });
        },
        handleSearchDialogClick() {
            search()
        },
        handleImportClick(e) {
            document.body.addEventListener('paste', handlePasteExcel)
            layer.open({
                type: 1,
                title: '批量粘贴',
                shadeClose: false,
                shade: [0.3, '#000'],
                maxmin: false,
                area: ['90%', '80%'],
                content: $('#batchPaste'),
                btn: ['确定导入', '关闭'],
                async yes(index){
                    document.body.removeEventListener('paste', handlePasteExcel)

                    if (store.excelData.length) {
                        let excelData = store.excelData
                        store.excelData = []

                        try {
                            const res = await axios.post('/cjCdwbh9Rel/importJSON', excelData)
                            if (res.data) {
                                layer.close(index)
                                pasteList.reload({data: []})

                                let temp_import_id = res.data
                                tmpStatusTable.reload({
                                    where: {
                                        temp_import_id,
                                        status: 0
                                    }
                                })

                                layer.open({
                                    type: 1,
                                    title: '数据有效性检查结果',
                                    area: ['850px', '700px'],
                                    content: $('#temporaryImportResult'),
                                    btn: ['导入有效记录', '取消'],
                                    async yes(i) {
                                        tmpStatusTable.reload({data: []})
                                        layer.close(i)

                                        try {
                                            const res = await axios.post(`/cjCdwbh9Rel/confirmImportData?importDataId=${temp_import_id}`)
                                            const {code, data, message} = res.data
                                            if (code === 1) {
                                                if (data === 0) {
                                                    layer.alert('没有有效数据可导入')
                                                } else {
                                                    layer.alert('导入成功')
                                                    mini.get('#datagrid').reload()
                                                }
                                            } else {
                                                layer.alert(message)
                                            }
                                        } catch (e) {
                                            console.error(e)
                                            layer.alert('服务异常，请联系管理员处理')
                                        }
                                    }
                                })
                            } else {
                                layer.msg('没有数据')
                            }
                        }
                        catch(e) {
                            console.log(e)
                            layer.close(index)
                            pasteList.reload({data: []})
                            layer.alert('服务异常，请联系管理员')
                        }
                    }
                    else {
                        layer.msg('没有数据')
                    }
                },
                btn2(){
                    document.body.removeEventListener('paste', handlePasteExcel)
                    pasteList.reload({data: []})
                },
            })
        }
    }).mount('.container')

    let handlePasteExcel = null
    let pasteList = null
    PetiteVue.createApp({
        datagridId: 'cc',
        toolbarId: 'hi',
        toolbarButtons: [
            {id: 'downloadTemplate', text: '下载模板', isPrimary: true},
            {id: 'clear', text: '全部清空', isDanger: true},
        ],
        mounted() {
            // initialize table
            pasteList = table.render({
                elem: `#${this.datagridId}`,
                toolbar: `#${this.toolbarId}`,
                height: 'full',
                limit: 10000,
                cols: [[
                    {type: 'numbers', title: '序号'},
                    {field: 'srcCdwbh9', title: '原客户编码前9位'},
                    {field: 'dstCdwbh9', title: '新客户编码前9位'}
                ]],
                data: []
            })
            // listen to click event of toolbar
            table.on(`toolbar(${this.datagridId})`, ({event}) => {
                this.handleToolbarClick(event)
            })

            handlePasteExcel = createPasteExcelHandler(data => {
                store.excelData = data.map(row => ({ srcCdwbh9: row[0], dstCdwbh9: row[1] }))
                pasteList.reload({data: store.excelData})
            })
        },
        handleToolbarClick(id) {
            if (id === 'downloadTemplate') {
                this.$refs.downloadTemplate.click()
            }
            else if (id === 'clear') {
                pasteList.reload({data: []})
            }
        }
    }).mount('#batchPaste')
})